package pyf.gaoji;

/**
 * @author pengyifeng
 * @version 5.1
 * @ClassName TestPcDemo2.java
 * @Description 生产者/消费者-标志法
 * @createTime 2021年07月27日 17:13:00
 */
public class TestPcDemo2 {
    public static void main(String[] args) {
        TV tv=new TV();
        new Shower(tv).start();
        new Watcher(tv).start();

    }

//生产者 演员
static class Shower extends Thread{
    TV tv;
    public Shower(TV tv){
        this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                if(i%2==0){

                    tv.play("向往的生活");
                }else{
                    tv.play("快乐大本营");
                }
            }catch (Exception e){
                e.getMessage();
            }

        }
    }
}
//消费者 观众
static class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                tv.watch();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
static class TV{
    //节目名
    String programName;
    //标志
    boolean flag=true;
//表演方法
private synchronized void play(String programName) throws InterruptedException {
    if(!flag){
        this.wait();
    }
    this.programName=programName;
    this.flag=!this.flag;
    this.notifyAll();
    System.out.println("演员表演了"+programName);
}
//观看方法
private synchronized void watch() throws InterruptedException {
    if(flag){
        this.wait();
    }
    this.programName=programName;
    this.flag=!this.flag;
    this.notifyAll();
    System.out.println("观众观看了"+programName);
}
}
}
